package com.we823.cms.repository.service.beetl.function;

import java.io.IOException;

import org.beetl.core.Context;
import org.beetl.core.Function;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.we823.cms.common.utils.StringUtil;

@Service("stringCut")
@Scope("prototype")
public class StringCutFunction implements Function {

	@Override
	public Object call(Object[] paras, Context ctx) {
		if (paras!=null && paras.length>0) {
			String source = (String) paras[0];
			Integer len = 16;
			String type="text";
			String append = "...";
			int length = paras.length;
			if (length>=2) {
				len = (Integer) paras[1];
			}
			
			if (length>=3) {
				type= (String) paras[2];
			}
			
			if (length>4) {
				append = (String) paras[3];
			}

			String finalString = "";
			if("text".equals(type)){
				finalString = StringUtil.textCut(source, len, append);
			}else{
				finalString = StringUtil.htmlCut(source, len, append);
			}
			
			try {
				ctx.byteWriter.writeString(finalString);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			return finalString;
		}
		return null;
	}

}
